﻿#region namespaces
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MS.InformationManagement.DAL.DocumentCenter;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;
using MS.InformationManagement.Support.Constants;
using System.Web.UI;
using MS.InformationManagement.Support;
using MS.InformationManagement.Core.Documentset;
using Microsoft.SharePoint.Taxonomy;
using MS.InformationManagement.Core.Support;
using MS.InformationManagement.Core.AssociatedActions;
using System.Collections;
using MS.InformationManagement.Support.FileCreator;
using MS.InformationManagement.Support.Enums;
using MS.InformationManagement.DAL.RecordCenter;
using MS.InformationManagement.Core.TransactionsResponse;
#endregion

namespace MS.InformationManagement.BLL.InsertarRadicadoSalida
{
    public class InsertarRadicadoSalida
    {
        /// <summary>
        /// Get the types of medios 
        /// </summary>
        /// <returns></returns>
        public List<ListItem> GetTypeMedios()
        {
            List<ListItem> listTypes = new List<ListItem>();

            SPFieldChoice field = (SPFieldChoice)SPContext.Current.Web.Fields[CustomSiteColumns.FIELD_DOCUMENT_MEDIO_DISPLAYNAME];

            for (int i = 0; i < field.Choices.Count; i++)
            {
                string choiceValue = field.Choices[i].ToString();
                listTypes.Add(new ListItem(choiceValue, i.ToString()));
            }

            return listTypes;
        }

        /// <summary>
        /// Show a pop up 
        /// </summary>
        /// <param name="Url">Url to show</param>
        /// <param name="Titulo">Titel of pop up</param>
        /// <param name="ancho"></param>
        /// <param name="alto"></param>
        /// <param name="pagina"></param>
        public void DesplegarVentanaModal(string Url, string Titulo, Int32 ancho, Int32 alto, Page pagina)
        {
            StringBuilder scriptModal = new StringBuilder();
            scriptModal.Append("var showMyModalDialog = function() { var options = { ");
            scriptModal.Append("url : '");
            scriptModal.Append(Url);
            scriptModal.Append("', ");
            scriptModal.Append("title: '");
            scriptModal.Append(Titulo);
            scriptModal.Append("', width: ");
            scriptModal.Append(ancho.ToString());
            scriptModal.Append(", height: ");
            scriptModal.Append(alto.ToString());
            scriptModal.Append(", dialogReturnValueCallback: onDialogClose }; SP.UI.ModalDialog.commonModalDialogOpen(" + "'" + Url + "'" + ",options, onDialogClose, null); };  function redirect(url){  location.replace(url);}  ");
            scriptModal.Append("function onDialogClose(dialogResult, returnValue) { ");
            scriptModal.Append(" SP.UI.ModalDialog.RefreshPage(SP.UI.DialogResult.OK);");
            //scriptModal.Append("redirect(location.href.split('?')[0] + '?rmtID=' +returnValue); ");
            scriptModal.Append(" } ");

            pagina.ClientScript.RegisterClientScriptBlock(pagina.GetType(), "Mensaje", scriptModal.ToString(), true);
            pagina.ClientScript.RegisterStartupScript(typeof(Page), "Precarga", "ExecuteOrDelayUntilScriptLoaded(showMyModalDialog, 'sp.ui.dialog.js');", true);
        }

        /// <summary>
        /// Get a sender by ID
        /// </summary>
        /// <param name="ID"></param>
        /// <returns></returns>
        public Contactos GetSender(string ID)
        {
            using (var dx = new DCDocumentCenterDataContext(SPContext.Current.Web.Url))
            {
                var contact = (from contacto in dx.ContactosExternos
                               where contacto.ID == ID
                               select contacto).FirstOrDefault();
                return contact;
            }
        }


        public ITransactionResponse SaveRadicadoEmpresaSalida(DAL.DocumentCenter.RadicadoEmpresaSalida Radicado)
        {
            return new RadicadoEmpresaSalidaActions(Radicado).NewRadicado();
        }
        public ITransactionResponse SaveRadicadoPersonaSalida(DAL.DocumentCenter.RadicadoPersonaSalida Radicado)
        {
            return new RadicadoPersonaSalidaActions(Radicado).NewRadicado();
        }

        public void UpdateRadicadoEmpresaSalida(DAL.DocumentCenter.RadicadoEmpresaSalida Radicado)
        {
            new RadicadoEmpresaSalidaActions(Radicado).UpdateRadicado();
        }
        public void UpdateRadicadoPersonaSalida(DAL.DocumentCenter.RadicadoPersonaSalida Radicado)
        {
            new RadicadoPersonaSalidaActions(Radicado).UpdateRadicado();
        }

        public DAL.DocumentCenter.RadicadoEmpresaSalida GetRadicadoEmpresaSalida(int IdRadicado, string currentLibrary)
        {
            RadicadoEmpresaSalidaActions radObject = new RadicadoEmpresaSalidaActions();
            radObject.CurrentLibrary = currentLibrary;
            return radObject.GetRadicado(IdRadicado);
        }
        public DAL.DocumentCenter.RadicadoPersonaSalida GetRadicadoPersonaSalida(int IdRadicado, string currentLibrary)
        {
            RadicadoPersonaSalidaActions radObject = new RadicadoPersonaSalidaActions();
            radObject.CurrentLibrary = currentLibrary;
            return radObject.GetRadicado(IdRadicado);
        }

        //public static int? getDepartmentCurrentUser()
        //{
        //    int? result = 0;
        //    string departamentoValue = PeopleHelper.GetPropertyUserProfile(GlobalConstants.UP_DEPARTMENT, SPContext.Current.Web.CurrentUser.LoginName);

        //    using (DataContext dx = new DataContext(SPContext.Current.Web.Url))
        //    {
        //        var foundSeccion = (from sec in dx.Secciones
        //                           where sec.Title == departamentoValue
        //                           orderby sec.Title ascending
        //                           select sec).FirstOrDefault();

        //        if(foundSeccion == null)
        //            throw new Exception("El departamento del usuario es invalido");

        //        result = foundSeccion.Id;
                    
        //    }
        //    return result;
        //}

        public static int? getDepartmentCurrentUser()
        {
            int? result = 0;
            string departamentoValue = PeopleHelper.GetPropertyUserProfile(GlobalConstants.UP_DEPARTMENT, SPContext.Current.Web.CurrentUser.LoginName);

            TRDSelector.TRDSelector trdbusinessObject = new TRDSelector.TRDSelector();
            Seccion currentUserSection = trdbusinessObject.GetSeccion(departamentoValue);
            
            result = currentUserSection.Id;

            return result;
        }

        public SPListItemCollection getChildFromRadicado(SPList ListaSource, string RadicadoID)
        {
            return DocumentSetHelper.getChildsFromDocumentSet(ListaSource, RadicadoID);
        }
        public static ITransactionResponse CreateRadicadoWithAssocitedAction(string action, Radicado radicado, List<string> associtedRadicados, string subjectExpediente)
        {
            IRadicado radObject;
            if (radicado is RadicadoPersonaSalida)
                radObject = new RadicadoPersonaSalidaActions((RadicadoPersonaSalida)radicado) { CurrentLibrary = UserLibraryHelper.CurrentUserLibraryName, CurrentContentType = GlobalConstants.CTTN_RADICADO_PERSONA_SALIDA };
            else
                radObject = new RadicadoEmpresaSalidaActions((RadicadoEmpresaSalida)radicado) { CurrentLibrary = UserLibraryHelper.CurrentUserLibraryName, CurrentContentType = GlobalConstants.CTTN_RADICADO_EMPRESA_SALIDA };

            if (action == "response")
                return new ResponseAsociation(associtedRadicados[0], null, UserLibraryHelper.CurrentUserLibraryName, radObject, radicado, subjectExpediente).Execute();
            if (action == "new")
                return new ExpedienteAsociation(associtedRadicados[0], null, UserLibraryHelper.CurrentUserLibraryName, radObject, radicado, subjectExpediente).Execute();


            return null;
        }

        public static IEnumerable<MedioDeEnvio> LoadMediosDeEnvio()
        {
            IEnumerable<MedioDeEnvio> foundMedios = null;

            using (DCDocumentCenterDataContext dx = new DCDocumentCenterDataContext(SPContext.Current.Web.Url))
            {
                foundMedios = (from medios in dx.MediosDeEnvio
                                 orderby medios.Title ascending
                                 select medios);
            }
            return foundMedios;
        }

        #region refactoring

        public String[] GetTipoRadicado()
        {
            String[] tipos = Enum.GetNames(typeof(TipoRemitente)).Where((val, idx) => idx != 1 && idx != 0).ToArray();
            return tipos;
        }

        public String[] GetModoRecepcionSalida()
        {
            string[] modos = Enum.GetNames(typeof(MedioRecepción)).Where((val, idx) => idx != 1 && idx != 0).ToArray();
            return modos;
        }

        #endregion
    }
}
